package com.jzo2o.orders.manager.service.client;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 自定义Feign客户端用于熔断降级
 * @author JIAN
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class MarketClient {
    @Resource
    private CouponApi couponApi;

    @SentinelResource(value = "availableCoupon",
            fallback = "getAvailableCouponFallback", blockHandler = "getAvailableCouponBlockHandler")
    public List<AvailableCouponsResDTO> getAvailableCoupon(BigDecimal totalAmount) {
        return couponApi.getAvailableCoupon(totalAmount);
    }

    public List<AvailableCouponsResDTO> getAvailableCouponFallback(BigDecimal totalAmount, Throwable throwable) {
        log.warn("优惠卷接口异常(未触发熔断), 总金额: {}", totalAmount, throwable);
        return null;
    }

    public List<AvailableCouponsResDTO> getAvailableCouponBlockHandler(BigDecimal totalAmount, BlockException blockException) {
        log.warn("优惠卷接口异常(触发熔断降级), 总金额: {}", totalAmount, blockException);
        return null;
    }

    @SentinelResource(value = "useCoupon",
            fallback = "useCouponFallback", blockHandler = "useCouponBlockHandler")
    public CouponUseResDTO useCoupon(CouponUseReqDTO couponUseReqDTO) {
        return couponApi.useCoupon(couponUseReqDTO);
    }

    public CouponUseResDTO useCouponFallback(CouponUseReqDTO couponUseReqDTO, Throwable throwable) {
        log.warn("优惠卷接口异常(未触发熔断), 相关信息: {}", couponUseReqDTO, throwable);
        return null;
    }

    public CouponUseResDTO useCouponBlockHandler(CouponUseReqDTO couponUseReqDTO, BlockException blockException) {
        log.warn("优惠卷接口异常(触发熔断降级), 相关信息: {}", couponUseReqDTO, blockException);
        return null;
    }
}